package com.gk.study.controller;

import com.gk.study.common.APIResponse;
import com.gk.study.common.ResponeCode;
import com.gk.study.entity.Homework;
import com.gk.study.entity.Thing;
import com.gk.study.service.HomeworkService;
import com.gk.study.service.ThingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/hwork")
public class HomeworkController {

    @Autowired
    private HomeworkService homeworkService;

    @Autowired
    ThingService thingService;




    // 获取教师发布的作业
    @GetMapping("/teacher/{teacherId}")
    public APIResponse<List<Homework>> getByTeacher(@PathVariable Long teacherId) {
        return new APIResponse<>(ResponeCode.SUCCESS, homeworkService.getHomeworkByTeacher(teacherId));
    }

    // 发布作业
    @PostMapping("/publish")
    public APIResponse<String> publish(@ModelAttribute Homework homework,
                                       @RequestParam(value = "file", required = false) MultipartFile file,
                                       @RequestHeader("user-id") String userId) { // 从请求头获取用户ID
        try {
            Thing thing = thingService.getThingByUserId(userId);
            if(thing == null) throw new RuntimeException("教师信息不存在");

            homework.setTeacherId(thing.getId()); // 设置实际教师ID
            homeworkService.publishHomework(homework, file);
            return APIResponse.success("发布成功");
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage());
        }
    }

    @GetMapping("/teacher")
    public APIResponse<List<Homework>> getByTeacher(@RequestHeader("user-id") String userId) {
        Thing thing = thingService.getThingByUserId(userId);
        if(thing == null) throw new RuntimeException("教师信息不存在");

        return new APIResponse<>(ResponeCode.SUCCESS,
                homeworkService.getHomeworkByTeacher(thing.getId()));
    }

    // 提交作业
    @PostMapping("/submit/{homeworkId}")
    public APIResponse<String> submit(@PathVariable Long homeworkId,
                                      @RequestParam String answer,
                                      @RequestParam(value = "file", required = false) MultipartFile file) {
        try {
            homeworkService.submitHomework(homeworkId, answer, file);
            return APIResponse.success("提交成功", "提交成功");
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage(), null);
        }
    }

    // 批改作业
    @PostMapping("/correct/{homeworkId}")
    public APIResponse<String> correct(@PathVariable Long homeworkId,
                                       @RequestParam Double score) {
        try {
            homeworkService.correctHomework(homeworkId, score);
            return APIResponse.success("批改成功", "批改成功");
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage(), null);
        }
    }

    // 获取教师已发布的作业（带课程信息）
    @GetMapping("/published")
    public APIResponse<List<Homework>> getPublishedHomework(
            @RequestHeader("user-id") Long userId) { // 当前登录用户ID
        try {
            Thing teacher = thingService.getThingByUserId(userId.toString());
            if(teacher == null) throw new RuntimeException("教师信息不存在");

            List<Homework> homeworkList = homeworkService.getPublishedHomeworkWithCourse(teacher.getId());
            return new APIResponse<>(ResponeCode.SUCCESS, homeworkList);
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage());
        }
    }

    // 根据作业ID获取详情（带批改信息）
    @GetMapping("/{id}")
    public APIResponse<Homework> getHomeworkDetail(
            @PathVariable Long id,
            @RequestHeader("user-id") Long userId) {
        Homework homework = homeworkService.getById(id);
        if(homework == null) return APIResponse.error("作业不存在");

        // 验证教师权限
        Thing teacher = thingService.getThingByUserId(userId.toString());
        if(!homework.getTeacherId().equals(teacher.getId())) {
            return APIResponse.error("无权限查看");
        }

        return APIResponse.success(homework);
    }

    // 学生作业查询接口
    @GetMapping("/student")
    public APIResponse<List<Homework>> getStudentHomework(
            @RequestParam Long studentId,
            @RequestParam(required = false) Integer status
    ) {
        try {
            List<Homework> homeworkList = homeworkService.getHomeworkByStudentAndStatus(studentId, status);
            return new APIResponse<>(ResponeCode.SUCCESS, homeworkList);
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage());
        }
    }


    // 获取学生成绩数据（带课程筛选）
    @GetMapping("/scores")
    public APIResponse<List<Homework>> getStudentScores(
            @RequestParam Long studentId,
            @RequestParam(required = false) String courseTitle
    ) {
        try {
            List<Homework> scores = homeworkService.getStudentScores(studentId, courseTitle);
            return new APIResponse<>(ResponeCode.SUCCESS, scores);
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage());
        }
    }

    // 获取学生有成绩的课程列表
    @GetMapping("/courses")
    public APIResponse<List<String>> getStudentCoursesWithScores(
            @RequestParam Long studentId
    ) {
        try {
            List<String> courses = homeworkService.getStudentCoursesWithScores(studentId);
            return new APIResponse<>(ResponeCode.SUCCESS, courses);
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage());
        }
    }


    // 教学分析接口
    @GetMapping("/analysis/students")
    public APIResponse<List<Long>> getTeachingStudents(
            @RequestParam String teacherUserId
    ) {
        try {
            List<Long> studentIds = homeworkService.getTeachingStudents(teacherUserId);
            return new APIResponse<>(ResponeCode.SUCCESS, studentIds);
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage());
        }
    }

    @GetMapping("/analysis/scores")
    public APIResponse<Map<String, List<Map<String, Object>>>> getTeachingAnalysisData(
            @RequestParam String teacherUserId,
            @RequestParam(required = false) Long studentId
    ) {
        try {
            Map<String, List<Map<String, Object>>> analysisData =
                    homeworkService.getTeachingAnalysisData(teacherUserId, studentId);
            return new APIResponse<>(ResponeCode.SUCCESS, analysisData);
        } catch (Exception e) {
            return new APIResponse<>(ResponeCode.FAIL, e.getMessage());
        }
    }

}